package com.lcxw.hxzbcommon.common;

import com.lcxw.hxzbcommon.entity.CommonBean;
import com.obs.services.ObsClient;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.PutObjectResult;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

@Slf4j
public class ObsUtil {

    private String endPoint;
    private String ak = "TEPZ5RHAPORK7NWI4AI9";
    private String sk = "SQpNvyhg6wFf1RlgeuH9kCx0ZaVvSkuvNCPF3Ioz";


    public ObsUtil(String endPoint, String ak, String sk) {
        this.endPoint = endPoint;
        this.ak = ak;
        this.sk = sk;
    }

    public ObsUtil(String endPoint) {
        this.endPoint = endPoint;
    }

    public ObsUtil() {
        this.endPoint = CommonBean.OBS_END_POINT;
    }

    public ObsClient getObsClient() {
        return new ObsClient(ak, sk, endPoint);
    }

    /**
     * @param imgName   上传后的图片全名包含后缀格式
     * @param imgOrigin 数据为将文件流转为字节数组后经base64加密的字符串
     * @return 上传后的图片访问链接，当前链接可保留时间在CommonBean中设置为3年
     * @throws Exception 异常统一捕获
     */
    public String uploadPic(String imgName, String imgOrigin) throws Exception {
        ObsClient obsClient = getObsClient();
        byte[] imgBytes;

        //对原始数据解码，获得字节数组
        imgBytes = new BASE64Decoder().decodeBuffer(imgOrigin);

        //使用字节流的方式将图片传到华为obs
        PutObjectResult putObjectResult = obsClient
            .putObject(CommonBean.OBS_BUCKET_NAME, imgName, new ByteArrayInputStream(imgBytes));
        //判断是否上传到华为OBS失败
        if (null == putObjectResult) {
            throw new Exception();
        }

        //上传成功后，需要获取该图片的下载url
        //生成图片url的过期时间，设置为3年
        long expireSeconds = CommonBean.IMGEXPIREDTIME;

        //下面是生成图片URL的方法
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET,
            expireSeconds);
        request.setBucketName(CommonBean.OBS_BUCKET_NAME);
        request.setObjectKey(imgName);
        TemporarySignatureResponse temporarySignatureResponse = obsClient
            .createTemporarySignature(request);
        return temporarySignatureResponse.getSignedUrl();
    }

    //通过上传流的方法，上传文件到obs
    public String uploadResrouce(String imgName, byte[] bytes) throws Exception {
        ObsClient obsClient = getObsClient();
        PutObjectResult putObjectResult = obsClient
            .putObject(CommonBean.OBS_BUCKET_NAME, imgName, new ByteArrayInputStream(bytes));
        //判断是否上传到华为OBS失败
        if (null == putObjectResult) {
            throw new Exception();
        }

        //上传成功后，需要获取该图片的下载url
        //生成图片url的过期时间，设置为3年
        long expireSeconds = CommonBean.IMGEXPIREDTIME;

        //下面是生成图片URL的方法
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET,
            expireSeconds);
        request.setBucketName(CommonBean.OBS_BUCKET_NAME);
        request.setObjectKey(imgName);
        TemporarySignatureResponse temporarySignatureResponse = obsClient
            .createTemporarySignature(request);
        return temporarySignatureResponse.getSignedUrl();
    }

    public static void main(String[] args) throws IOException {

//        String path = "F:\\03_素材\\轮播";
//        File[] files = getFile(path);
//        for (int i = 0; i < files.length; i++) {
//            String name = files[i].getName();
//            upload(path, name);
//        }

//        for (int i = 1; i <= 1; i++) {
//            upload("F:\\03_素材\\1", "" + i, "png");
//        }

//        upload("F:\\03_素材\\静态礼物", "钻石.png");
//        upload("F:\\03_素材\\静态礼物", "四叶草.png");
        upload("F:\\03_素材\\静态礼物", "四叶草.png");
    }

    static void upload(String path, String name) throws IOException {

        String objKey = "test/test/";
        String outPutPath = "F:\\carousel.txt";

        String endPoint = "obs.cn-east-2.myhuaweicloud.com";
        String ak = "TEPZ5RHAPORK7NWI4AI9";
        String sk = "SQpNvyhg6wFf1RlgeuH9kCx0ZaVvSkuvNCPF3Ioz";
        ObsUtil obsUtil = new ObsUtil(endPoint, ak, sk);
        ObsClient obsClient = obsUtil.getObsClient();
        File pic1 = new File(path + "\\" + name);
        PutObjectResult test1 = obsClient
            .putObject(CommonBean.OBS_BUCKET_NAME, objKey + name, pic1);
        System.out.println(test1);

        long expireSeconds = 36000000L;

        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET,
            expireSeconds);
        request.setBucketName(CommonBean.OBS_BUCKET_NAME);
        request.setObjectKey(objKey + name);

        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        String url = response.getSignedUrl();

        File urls = new File(outPutPath);
        FileWriter fileWriter = new FileWriter(urls, true);
        fileWriter.write(name + ":\r\n\r\n" + url + "\r\n\r\n");
        fileWriter.flush();
        fileWriter.close();
        obsClient.close();
    }

    private static File[] getFile(String path) {
        // get file list where the path has
        File file = new File(path);
        // get the folder list
        return file.listFiles();

//        for (int i = 0; i < array.length; i++) {
//            if (array[i].isFile()) {
//                // only take file name
////                System.out.println("^^^^^" + array[i].getName());
////                // take file path and name
////                System.out.println("#####" + array[i]);
////                // take file path and name
////                System.out.println("*****" + array[i].getPath());
//            }
////            else if (array[i].isDirectory()) {
////                getFile(array[i].getPath());
////            }
//        }
    }

}
